package postpic.domain;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import postpic.json.JSONSerializable;

public class Photo implements JSONSerializable {
	
	private Integer photoId;
	private Integer userId;
	private String photoUrl;
	private String caption;
	private Date dateAdded;
	private List<Comment> comments;
	
	public Photo() {
		
	}

	public Integer getPhotoId() {
		return photoId;
	}

	public void setPhotoId(Integer photoId) {
		this.photoId = photoId;
	}

	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public String getPhotoUrl() {
		return photoUrl;
	}

	public void setPhotoUrl(String photoUrl) {
		this.photoUrl = photoUrl;
	}

	public String getCaption() {
		return caption;
	}

	public void setCaption(String caption) {
		this.caption = caption;
	}

	public Date getDateAdded() {
		return dateAdded;
	}

	public void setDateAdded(Date dateAdded) {
		this.dateAdded = dateAdded;
	}
	
	public List<Comment> getComments(){
		return comments;
	}
	
	public void setComments(List<Comment> comments) {
		this.comments = comments;
	}

	@Override
	public JSONObject getJSON() {
		JSONObject json = new JSONObject();
		json.put("photoId", photoId);
		json.put("userId", userId);
		json.put("photoUrl", photoUrl);
		json.put("caption", caption);
		json.put("dateAdded", dateAdded.getTime());
		
		JSONArray commentArray = new JSONArray();
		for (Comment c : comments) {
			commentArray.put(c.getJSON());
		}
		
		json.put("comments", commentArray);
		
		return json;
	}

	@Override
	public void populateFromJSON(JSONObject json) {
		setPhotoId(json.getInt("photoId"));
		setUserId(json.getInt("userId"));
		setPhotoUrl(json.getString("photoUrl"));
		setCaption(json.getString("caption"));
		setDateAdded(new Date(json.getLong("dateAdded")));
		
		List<Comment> c = new ArrayList<Comment>();
		JSONArray cArray = json.getJSONArray("comments");
		
		for (int i = 0; i < cArray.length(); i++) {
			c.add(new Comment(cArray.getJSONObject(i)));
		}
		
		setComments(c);
		
	}
	
	@Override
	public String toString(){
		return getJSON().toString();
	}
	
	

}
